﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Threading;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.Entities.LocalDatabase;
using ComicIsland.Common.StorageHelper;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework.Media;

namespace ComicIsland.App.Views.ReadComicImage
{
    public partial class ComicReadPage : PhoneApplicationPage
    {
        private int comicId, comicPartId, bookId;
        private string comicTitle = string.Empty, comicPartTitle = string.Empty;
        private ObservableCollection<LDBComicChapterImage> dbImages = new ObservableCollection<LDBComicChapterImage>();
        //
        //        private int currentDbImageIndex = 0;
        private JsonComicDetailComicsdetail currentComic;
        private JsonComicChapterInfoBookPartList currentComicChapter;
        //
        private double ImageHeight = Application.Current.Host.Content.ActualHeight;
        private double ImageWeight = Application.Current.Host.Content.ActualWidth;

        public ComicReadPage()
        {
            InitializeComponent();
            //
            this.middleImage.Height = this.ImageHeight;
            this.middleImage.Width = this.ImageWeight - 2;
            this.middleImage.Margin = new Thickness(1, 0, 1, 0);
            //
            this.pTapFairy.Interval = (TimeSpan.FromMilliseconds(100));
            this.pTapFairy.Tick += delegate(object o, EventArgs args)
            {
                this.FairyTurnPage();
            };
            AddManipulation();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string tmpComicId, tmpBookId, tmpComicPartId;
            base.NavigationContext.QueryString.TryGetValue("comicId", out tmpComicId);
            int.TryParse(tmpComicId, out comicId);
            base.NavigationContext.QueryString.TryGetValue("bookId", out tmpBookId);
            int.TryParse(tmpBookId, out bookId);
            base.NavigationContext.QueryString.TryGetValue("comicPartId", out tmpComicPartId);
            int.TryParse(tmpComicPartId, out comicPartId);
            if (comicId <= 0 || bookId <= 0 || this.comicPartId <= 0)
            {
                if (base.NavigationService.CanGoBack)
                {
                    base.NavigationService.GoBack();
                }
                return;
            }
            base.NavigationContext.QueryString.TryGetValue("comicTitle", out comicTitle);
            //
            LoadComicImage();
            //
            base.OnNavigatedTo(e);
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (this.popupBrightness.IsOpen || this.popupContent.IsOpen || this.popupProgress.IsOpen || this.popupShared.IsOpen)
            {
                SetPopupOpenStatus(false);
                e.Cancel = true;
            }

            base.OnBackKeyPress(e);
        }

        private void SetPopupOpenStatus(bool isOpen)
        {
            this.popupBrightness.IsOpen = isOpen;
            this.popupContent.IsOpen = isOpen;
            this.popupProgress.IsOpen = isOpen;
            this.popupShared.IsOpen = isOpen;
            this.ApplicationBar.IsVisible = isOpen;
        }


        #region 加载漫画数据
        /// <summary>
        /// 读取漫画图片
        /// <para>有缓存时则直接读取缓存中的数据</para>
        /// <para>无缓存则直接连接查询</para>
        /// </summary>
        private void LoadComicImage()
        {
            //
            LoadComic();
        }

        #region 加载漫画详细数据
        void LoadComic()
        {
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/comicsdetail_v2?bigbookid=", this.comicId, "&", KEYS.REQUEST_QUERY_PLATFORM);

            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicDetailBase>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Comicsdetail != null && rootCharacterString.Info.Comicsdetail.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    //加入缓存下载队列
                    var items = rootCharacterString.Info.Comicsdetail;
                    if (items != null && items.Count > 0)
                    {
                        currentComic = (from p in items select p).FirstOrDefault<JsonComicDetailComicsdetail>();
                    }
                }
                this.LoadComicChapter(this.comicPartId);
                return;
            }
            //
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);     
                            this.txtLoadingToolTip.Text = "未获取到数据";
                        }
                        else if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);                            
                        }
                        else
                        {
                            LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                            if (result.IndexOf("\"info\":{}") >= 0)
                            {
                                LogHelper.LogError("未找到对应漫画！", this.GetType(), MethodBase.GetCurrentMethod());
                            }
                            else
                            {
                                var rootCharacterString = JSONHelper.Deserialize<JsonComicDetailBase>(result);
                                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Comicsdetail != null && rootCharacterString.Info.Comicsdetail.Count > 0))
                                {
                                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                                }
                                else
                                {
                                    var items = rootCharacterString.Info.Comicsdetail;
                                    if (items != null && items.Count > 0)
                                    {
                                        cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                        //加入缓存下载队列
                                        currentComic = (from p in items select p).FirstOrDefault<JsonComicDetailComicsdetail>();
                                    }
                                }
                            }
                        }
                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {
                        LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                    }
                    finally
                    {
                        this.LoadComicChapter(this.comicPartId);
                    }
                });
            }, webTask);
        }

        void LoadComicChapter(int comicChapterId, bool IsBindChapterList = false)
        {
            this.comicPartId = comicChapterId;
            if (this.currentComic == null)
            {
                return;
            }
            //
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/downloadcomicsview_v3?bookid=", this.bookId, "&", KEYS.REQUEST_QUERY_PLATFORM);

            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                //无需重新加载数据
                var rootCharacterString = JSONHelper.Deserialize<JsonComicChapter>(cacheHelper.LocalCacheData);
                if (rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.BookPartList != null && rootCharacterString.Info.BookPartList.Count > 0)
                {
                    if (IsBindChapterList)
                    {
                        this.llsContent.ItemsSource = rootCharacterString.Info.BookPartList;
                    }
                    this.currentComicChapter = (from p in rootCharacterString.Info.BookPartList where p.PartId == this.comicPartId select p).FirstOrDefault<JsonComicChapterInfoBookPartList>();
                }
                this.LoadComicChapterImage();
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region ********************获取结果处理********************
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        if (result.IndexOf("\"info\":{}") >= 0)
                        {
                            LogHelper.LogError("未找到对应漫画！", this.GetType(), MethodBase.GetCurrentMethod());
                            return;
                        }
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicChapter>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.BookPartList != null && rootCharacterString.Info.BookPartList.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                            if (IsBindChapterList)
                            {
                                this.llsContent.ItemsSource = rootCharacterString.Info.BookPartList;
                            }
                            this.currentComicChapter = (from p in rootCharacterString.Info.BookPartList where p.PartId == this.comicPartId select p).FirstOrDefault<JsonComicChapterInfoBookPartList>();
                        }
                        #endregion ********************获取结果处理********************
                    });
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                }
                finally
                {
                    this.LoadComicChapterImage();
                }
            }, webTask);
        }

        void LoadComicChapterImage()
        {
            if (this.currentComic == null || this.currentComicChapter == null)
            {
                LogHelper.LogError("获取漫画数据失败！");
                return;
            }

            string requestUrl = string.Concat(KEYS.REQUEST_HOST, string.Format("/comic/comicsread_v3?bookid={0}&partid={1}&partVersion=3", this.bookId, this.currentComicChapter.PartId), "&", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                //无需重新加载数据
                var rootCharacterString = JSONHelper.Deserialize<JsonComicContent>(cacheHelper.LocalCacheData);
                if (rootCharacterString != null && !string.IsNullOrWhiteSpace(rootCharacterString.Info))
                {
                    var itemsource = JSONHelper.Deserialize<ObservableCollection<JsonComicContentInfo>>(rootCharacterString.Info);
                    BindComicChapterImage(itemsource);
                }
                return;
            }

            //
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        #region **********获取结果处理**********
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //

                        var rootCharacterString = JSONHelper.Deserialize<JsonComicContent>(result);
                        if (rootCharacterString != null && !string.IsNullOrWhiteSpace(rootCharacterString.Info))
                        {
                            var itemsource = JSONHelper.Deserialize<ObservableCollection<JsonComicContentInfo>>(rootCharacterString.Info);
                            BindComicChapterImage(itemsource);
                        }
                        #endregion **********获取结果处理**********
                    });
                }
                catch (Exception err)
                {

                }
            }, webTask);
        }

        void BindComicChapterImage(ObservableCollection<JsonComicContentInfo> items)
        {
            this.dbImages = new ObservableCollection<LDBComicChapterImage>();

            if (items != null && items.Count > 0)
            {
                foreach (JsonComicContentInfo jcci in items)
                {
                    if (jcci == null)
                        continue;
                    this.dbImages.Add(new LDBComicChapterImage()
                    {
                        ComicId = this.comicId,
                        BookId = this.bookId,
                        PartId = comicPartId,
                        ImageUrl = jcci.Imgurl,
                        Referer = jcci.Referer,
                        ComicIdAndBookIdAndPartId = string.Concat(comicId, "#", this.bookId, "#", comicPartId),
                        ComicName = this.currentComic.BigbookName,
                        PartName = this.currentComicChapter.Name
                    });
                }
            }

            this.BindImageToControl();
        }

        void BindImageToControl()
        {
            if (!(this.currentComic != null && this.currentComicChapter != null && this.dbImages != null && this.dbImages.Count > 0))
            {
                MessageToastManager.Show("加载漫画数据失败！");
                return;
            }
            //
            this.sliderPopupProgress.Maximum = this.dbImages.Count;
            this.sliderPopupProgress.Value = 1;
            //初始化
            this.middleImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[0]);
            this.middleImage.Tag = 0;
            if (this.dbImages.Count > 1)
                this.rightImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[1], true);
        }
        #endregion 加载漫画详细数据

        #endregion 加载漫画数据


        #region 绑定图片至控件
        private void DownloadImageToCache(LDBComicChapterImage dbImage, Image imageControl)
        {
            try
            {
                string filePath = string.Concat(KEYS.ComicIslandCacheDirectory, "/", KEYS.CacheImagePrefix, dbImage.ComicId, "_", dbImage.PartId, "_", MD5.GetMd5String(dbImage.ImageUrl));
                if (IsolatedStorageHelper.Instance.FileExists(filePath))
                {
                    return;//已经缓存了
                }

                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.UriSource = new Uri(dbImage.ImageUrl, UriKind.Absolute);//取网络图片  
                imageControl.Source = bitmapImage;
                bitmapImage.ImageOpened += delegate(object sender, RoutedEventArgs e)
                {
                    this.ImageOpenedAndSaveImage(bitmapImage, filePath);
                };
            }
            catch { }
        }
        private BitmapImage LoadBitmapImageFromDbImage(LDBComicChapterImage dbImage, bool IsBackgroudLoad = false)
        {
            string filePath = string.Concat(KEYS.ComicIslandCacheDirectory, "/", KEYS.CacheImagePrefix, dbImage.ComicId, "_", dbImage.PartId, "_", MD5.GetMd5String(dbImage.ImageUrl));
            BitmapImage bitmapImage = new BitmapImage();
            try
            {
                if (!IsolatedStorageHelper.Instance.FileExists(filePath))
                {
                    if (!IsBackgroudLoad)
                    {
                        this.gridLoading.Visibility = System.Windows.Visibility.Visible;
                        LogHelper.LogInfo(string.Concat("加载网络图片！", dbImage.ImageUrl));
                        bitmapImage.UriSource = new Uri(dbImage.ImageUrl, UriKind.Absolute);//取网络图片                        
                        bitmapImage.ImageOpened += delegate(object sender, RoutedEventArgs e)
                        {
                            LogHelper.LogInfo("bitmapImage_ImageOpened");
                            this.txtLoadingToolTip.Text = AppResources.ComicReadPageLoading;
                            this.gridLoading.Visibility = System.Windows.Visibility.Collapsed;
                            this.ImageOpenedAndSaveImage(bitmapImage, filePath);
                        };
                        bitmapImage.DownloadProgress += delegate(object sender, DownloadProgressEventArgs e)
                        {
                            this.txtLoadingToolTip.Text = string.Concat("请稍候，已加载 ", e.Progress, "%");
                        };
                        bitmapImage.ImageFailed += delegate(object sender, ExceptionRoutedEventArgs e)
                        {
                            this.txtLoadingToolTip.Text = AppResources.ComicReadPageLoading;
                            this.gridLoading.Visibility = System.Windows.Visibility.Collapsed;
                            MessageToastManager.Show("加载失败！");
                        };
                    }
                    else
                    {
                        //缓存下一张
                        this.DownloadImageToCache(dbImage, this.rightImage);
                        //缓存下下张
                        int cacheIndex = int.Parse(this.middleImage.Tag.ToString()) + 2;
                        if (cacheIndex < this.dbImages.Count)
                        {
                            this.DownloadImageToCache(this.dbImages[cacheIndex], this.cacheImage);
                        }
                    }
                }
                else
                {
                    try
                    {
                        using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            using (IsolatedStorageFileStream isoStream = store.OpenFile(filePath, FileMode.Open))
                            {
                                Stream fileStream = new MemoryStream();
                                isoStream.CopyTo(fileStream);
                                isoStream.Close();
                                isoStream.Dispose();
                                store.Dispose();
                                bitmapImage.SetSource(fileStream);
                                this.gridLoading.Visibility = System.Windows.Visibility.Collapsed;
                            }
                        }
                    }
                    catch { }
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }

            return bitmapImage;
        }


        /// <summary>
        /// BitmapImage转换为文件存储
        /// </summary>
        /// <param name="bitmapImage"></param>
        /// <param name="filePath"></param>
        void ImageOpenedAndSaveImage(BitmapImage bitmapImage, string filePath)
        {
            try
            {
                var writeableBitmap = new WriteableBitmap(bitmapImage);
                using (var isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
                using (IsolatedStorageFileStream fileStream = isolatedStorageFile.OpenFile(filePath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    writeableBitmap.SaveJpeg(fileStream, (int)bitmapImage.PixelWidth, (int)bitmapImage.PixelHeight, 0, 100);
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }
            catch { }
            finally
            { }
        }
        #endregion 绑定图片至控件


















        #region ******************************ApplicationBar******************************

        #region ********************目录列表********************
        private void appBarComicContents_Click(object sender, EventArgs e)
        {
            this.popupProgress.IsOpen = false;
            //
            this.LoadComicChapter(0, true);
            if (this.currentComic != null)
                this.txtPopupContentTitle.Text = this.currentComic.BigbookName;
            this.popupContent.IsOpen = !this.popupContent.IsOpen;
        }

        private void imageClosePopup_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.popupContent.IsOpen = false;
        }

        private void btnChapterSelected_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (sender as Button).DataContext as JsonComicChapterInfoBookPartList;
            if (item == null)
            {
                return;
            }
            if (this.comicPartId == item.PartId)
            {
                return;//选择仍然是当前阅读章节
            }
            this.popupContent.IsOpen = false;
            this.comicPartId = item.PartId;
            this.comicPartTitle = item.Name;
            this.LoadComicChapter(this.comicPartId);
        }
        #endregion ********************目录列表********************

        #region ********************进度跳转********************
        private void sliderPopupProgress_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                this.txtCurrentSliderPopupProgress.Text = ((int)e.NewValue).ToString();
            });
        }

        private void sliderPopupProgress_LostMouseCapture(object sender, System.Windows.Input.MouseEventArgs e)
        {
            int newValue = (int)(e.OriginalSource as Slider).Value - 1;
            int currentValue = Convert.ToInt32(this.middleImage.Tag);//当前图片位置
            if (currentValue == newValue)
            {
                return;
            }
            if (currentValue < newValue)
            {
                //下一页                
                if (newValue <= 0)
                    newValue = 0;
                //因为sliderPopupProgress的有+1,所以索引位要多处理一个
                if ((newValue - 1) < this.dbImages.Count)
                {
                    this.middleImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[newValue - 1]);
                    this.middleImage.Tag = newValue - 1;
                }
                if (newValue - 2 >= 0)
                    this.leftImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[newValue - 2]);
                if ((newValue) < this.dbImages.Count)
                {
                    this.rightImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[newValue], true);
                }
                LogHelper.LogInfo("LostMouseCapture.Next:\t" + this.middleImage.Tag.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                return;
            }
            if (currentValue > newValue)
            {
                //上一页                
                if (newValue <= 0)
                    newValue = 0;
                if (newValue < this.dbImages.Count)
                {
                    this.middleImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[newValue]);
                    this.middleImage.Tag = newValue;
                }
                if (newValue - 1 >= 0)
                {
                    this.leftImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[newValue - 1]);
                }
                if ((newValue + 1) < this.dbImages.Count)
                {
                    this.rightImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[newValue + 1], true);
                }


                return;
            }
        }


        #endregion ********************进度跳转********************

        #region ********************亮度调节********************
        private void appBarBrightness_Click(object sender, EventArgs e)
        {
            this.popupContent.IsOpen = false;
            this.popupProgress.IsOpen = false;
            this.popupBrightness.IsOpen = !this.popupBrightness.IsOpen;
        }

        private void sliderpopupBrightness_LostMouseCapture(object sender, System.Windows.Input.MouseEventArgs e)
        {

        }

        private void sliderpopupBrightness_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            this.gridBrightness.Opacity = e.NewValue;
        }
        #endregion ********************亮度调节********************

        /// <summary>
        /// 固定至桌面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appBarComicPinShellTile_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.currentComic == null)
                {
                    MessageToastManager.Show("操作失败！", MessageToastLevel.Error);
                    return;
                }
                string navigationUrl = string.Format("/Views/{0}.xaml?comicId={1}&IsShellTile=1", ComicIslandPage.ComicSummaryPage.ToString(), this.currentComic.BigbookId);
                ShellTile shellTile = ShellTile.ActiveTiles.FirstOrDefault<ShellTile>((ShellTile p) => p.NavigationUri.ToString().Equals(navigationUrl));
                if (shellTile != null)
                {
                    MessageToastManager.Show("桌面已经有了这本漫画哦！");
                    return;
                }
                StandardTileData standardTileData = new StandardTileData();
                standardTileData.Title = this.comicTitle;
                standardTileData.BackgroundImage = (new Uri(this.currentComic.Coverurl, UriKind.Absolute));
                //standardTileData.BackBackgroundImage = (new Uri(this.comicCoverUrl, UriKind.Absolute));
                //standardTileData.BackTitle = this.comicTitle;
                //standardTileData.BackContent = this.comicTitle;
                ShellTile.Create(new Uri(navigationUrl, UriKind.Relative), standardTileData);
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>
        /// 显示阅读帮助图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appBarHelper_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 意见反馈
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appBarFeedback_Click(object sender, EventArgs e)
        {
            NaviService.Navigate(ComicIslandPage.OtherComicFeedbackPage);
        }

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appBarSavePictures_Click(object sender, EventArgs e)
        {
            try
            {
                var item = this.dbImages[Convert.ToInt32(this.middleImage.Tag)];
                WriteableBitmap writeableBitmap = new WriteableBitmap(this.middleImage.Source as BitmapSource);
                using (MemoryStream stream = new MemoryStream())
                {
                    writeableBitmap.SaveJpeg(stream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);
                    //int startIndex = item.ImageUrl.LastIndexOf("/");
                    //string extName = item.ImageUrl.Substring(startIndex, item.ImageUrl.Length - startIndex);
                    //string filename = string.Format("{0}_{1}_{2}_{3}", this.comicTitle, this.comicPartId, item.PartName, extName);
                    MediaLibrary library = new MediaLibrary();
                    library.SavePicture(new Random().Next(1, 10000).ToString(), stream.ToArray());
                    //Picture picture = library.SavePictureToCameraRoll(filename, stream.ToArray());
                }
                MessageToastManager.Show("保存图片成功！");
            }
            catch
            {
                MessageToastManager.Show("保存图片失败！");
            }
        }

        /// <summary>
        /// 截图分享
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appBarShared_Click(object sender, EventArgs e)
        {
            try
            {
                ShareData shareData = new ShareData();
                shareData.Content = string.Format("报告大王！，在漫画岛发现神作《{0}》，满满全是真(bi)爱(ge)！下载地址：http://www.manhuadao.cn", this.comicTitle);
                shareData.ImageSavedType = (int)ImageLocationType.Iso; ;
                var item = this.dbImages[Convert.ToInt32(this.middleImage.Tag)];
                shareData.ImageUrl = string.Concat(KEYS.ComicIslandCacheDirectory, "/", KEYS.CacheImagePrefix, item.ComicId, "_", item.PartId, "_", MD5.GetMd5String(item.ImageUrl));
                this.sharedControl.shareData = shareData;
                this.sharedControl.OnClose += delegate(object s1, EventArgs e1)
                {
                    this.popupShared.IsOpen = false;
                };
                this.popupShared.IsOpen = true;
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }
        #endregion ******************************ApplicationBar******************************




        #region ******************************手势绽放控制******************************
        private bool Mutexes = false;
        private bool isPinch;
        private bool isDrag;
        public bool IsDragHorizontal = true;
        private bool isGestureOnTarget;
        private bool pIsDoubleTap;
        private Point _ePoint;
        private Point _cPoint;
        private bool pIsTap;//单击还是双击
        private DispatcherTimer pTapFairy = new DispatcherTimer();
        private System.Windows.Input.GestureEventArgs gesture;

        private void FairyTurnPage()
        {
            try
            {
                if (!this.pIsDoubleTap)
                {
                    Point position = this.gesture.GetPosition(this);
                    LogHelper.LogInfo("单击：FairyTurnPage:\t" + position.X + "_Y:" + position.Y);
                    this.OnNavigateImagePosition(position);
                }
            }
            catch
            {
            }
            finally
            {
                this.pIsTap = false;
                this.pIsDoubleTap = false;
                this.pTapFairy.Stop();
            }
        }

        #region ********************Manipulation********************
        void AddManipulation()
        {
            this.ManipulationDelta += OnManipulationDelta;
            this.ManipulationStarted += OnManipulationStarted;
            this.ManipulationCompleted += OnManipulationCompleted;
            this.LayoutRoot.Tap += OnTap;
        }

        void RemoveManipulation()
        {
            this.ManipulationDelta -= OnManipulationDelta;
            this.ManipulationStarted -= OnManipulationStarted;
            this.ManipulationCompleted -= OnManipulationCompleted;
            this.LayoutRoot.Tap += OnTap;
        }

        private void OnManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            bool flag = this.isPinch;
            bool flag1 = this.isDrag;
            this.isPinch = e.PinchManipulation != null;
            this.isDrag = (e.PinchManipulation != null ? false : !flag);
            if (flag1)
            {
                bool flag2 = this.isDrag;
            }
            if (flag1 && this.isDrag)
            {
                this.OnDragDelta(sender, e);
            }
            if (flag && !this.isPinch)
            {
                this.OnPinchCompleted();
            }
            if (flag && this.isPinch)
            {
                this.OnPinchDelta(sender, e);
            }
            if (!flag1 && this.isDrag)
            {
                Rect rect = new Rect(0, 0, this.LayoutRoot.ActualWidth, this.LayoutRoot.ActualHeight);
                this.isGestureOnTarget = rect.Contains(e.ManipulationOrigin);
                this.OnDragStarted(e);
            }
            if (!flag && this.isPinch)
            {
                Rect rect1 = new Rect(0, 0, this.LayoutRoot.ActualWidth, this.LayoutRoot.ActualHeight);
                this.isGestureOnTarget = rect1.Contains(e.PinchManipulation.Original.PrimaryContact);
                this.OnPinchStarted(sender, e);
            }
        }

        private void OnManipulationStarted(object sender, System.Windows.Input.ManipulationStartedEventArgs e)
        {
        }

        private void OnManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e)
        {
            //e.Handled = true;
            //拖动
            if (this.isDrag)
            {
                this.isDrag = false;
                this.OnDragCompleted();
                if (e.IsInertial)
                {
                    this.OnFlick(sender, e);
                }
            }
            //手势缩放
            if (this.isPinch)
            {
                this.isPinch = false;
                this.OnPinchCompleted();
            }
            //
            if (!this.IsDoubleScale)
            {
                if (e.TotalManipulation.Translation.X != 0)
                {
                    Point point = e.ManipulationContainer.TransformToVisual(this).Transform(e.ManipulationOrigin);
                    double xTotal = e.TotalManipulation.Translation.X;
                    LogHelper.LogInfo("OnManipulationCompleted:\t" + e.TotalManipulation.Translation.X);
                    OnNavigateImagePosition(point, xTotal);
                }
            }
        }

        private void OnTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (this.Mutexes || !this.IsDragHorizontal)
            {
                return;
            }
            this.pIsDoubleTap = false;
            if (!this.pIsTap)
            {
                this.pIsTap = true;
                this.gesture = e;
                this.pTapFairy.Start();
            }
        }

        private void OnNavigateImagePosition(Point position, double xTotal = 0)
        {
            int currentImagePosition = Convert.ToInt32(this.middleImage.Tag);
            //弹出菜单层
            if (xTotal == 0 && position.X > 120 && position.X < 360 && position.Y > 300 && position.Y < 500)
            {
                LogHelper.LogInfo("ApplicationBar");                
                this.ApplicationBar.IsVisible = !this.ApplicationBar.IsVisible;
                this.popupProgress.IsOpen = this.ApplicationBar.IsVisible;
                string popupTitle = string.Empty;
                if (this.currentComic != null)
                    popupTitle += this.currentComic.BigbookName;
                if (this.currentComicChapter != null)
                    popupTitle += " " + this.currentComicChapter.Name;
                this.txtPopupProgressTitle.Text = popupTitle;
                this.txtPopupBrightnessTitle.Text = popupTitle;
            }
            //单击翻页
            else
            {
                SetPopupOpenStatus(false);
                if (xTotal == 0 && ((position.X <= 240 && position.Y <= 300) || (position.X <= 120 && position.Y >= 300 && position.Y <= 500) || (position.Y >= 500 && position.X <= 240)))
                {
                    if (currentImagePosition <= 0)
                        MessageToastManager.Show("已经是本章节的首页了！");
                    else
                    {
                        //上一页
                        LogHelper.LogInfo("Next");
                        SetImageNextOrPrevious(NextOrPrevious.Previous);
                    }
                }
                else if (xTotal == 0 && ((position.X > 240 && position.Y <= 300) || (position.X >= 360 && position.Y >= 300 && position.Y <= 500) || (position.Y >= 500 && position.X > 240)))
                {
                    if ((currentImagePosition + 1) > this.dbImages.Count - 1)
                        MessageToastManager.Show("已经是本章节的最后一页了！");
                    else
                    {
                        //下一页
                        LogHelper.LogInfo("Next");
                        SetImageNextOrPrevious(NextOrPrevious.Next);
                    }
                }
                //手势滑动翻页
                else if (xTotal < 0)
                {
                    if ((currentImagePosition + 1) > this.dbImages.Count - 1)
                        MessageToastManager.Show("已经是本章节的最后一页了！");
                    else
                    {
                        LogHelper.LogInfo("Next");
                        SetImageNextOrPrevious(NextOrPrevious.Next);
                    }
                }
                else if (xTotal > 0)
                {
                    if (currentImagePosition <= 0)
                        MessageToastManager.Show("已经是本章节的首页了！");
                    else
                    {
                        LogHelper.LogInfo("Previous");
                        SetImageNextOrPrevious(NextOrPrevious.Previous);
                    }
                }
            }
        }

        public enum NextOrPrevious
        {
            Next,
            Previous
        }

        private void SetImageNextOrPrevious(NextOrPrevious nextOrPrevious)
        {
            int currentImagePosition = Convert.ToInt32(this.middleImage.Tag);
            //
            if (nextOrPrevious == NextOrPrevious.Previous)
            {
                if (currentImagePosition <= 0)
                {
                    currentImagePosition = 0;
                    return;
                }
                if (currentImagePosition - 2 >= 0)
                {
                    this.leftImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[currentImagePosition - 2]);
                }
                if (currentImagePosition - 1 >= 0)
                {
                    this.middleImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[currentImagePosition - 1]);
                    this.middleImage.Tag = currentImagePosition - 1;
                }
                this.rightImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[currentImagePosition], true);
            }
            else if (nextOrPrevious == NextOrPrevious.Next)
            {
                if (currentImagePosition < 0)
                    currentImagePosition = 0;
                this.leftImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[currentImagePosition]);

                //LogHelper.LogInfo("Next:\t" + this.currentDbImageIndex, this.GetType(), MethodBase.GetCurrentMethod());
                if ((currentImagePosition + 1) < this.dbImages.Count)
                {
                    this.middleImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[currentImagePosition + 1]);
                    this.middleImage.Tag = currentImagePosition + 1;
                }
                if ((currentImagePosition + 2) < this.dbImages.Count)
                {
                    this.rightImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[currentImagePosition + 2], true);
                }
            }
            //            LogHelper.LogInfo("......." + Convert.ToInt32(this.middleImage.Tag).ToString());
            this.sliderPopupProgress.Value = Convert.ToInt32(this.middleImage.Tag) + 1;//因为是从零开始计数
        }
        #endregion ********************Manipulation********************


        #region ********************手势拖拽********************
        private Point _oPoint;
        public double DistanceY;
        private void OnDragStarted(System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            if (this.isGestureOnTarget)
            {
                //if (this.sbOperator != null)
                //{
                //    this.sbOperator.Pause();
                //}
                Point point = new Point(0, 0);
                Point point1 = point;
                this._cPoint = point;
                this._ePoint = point1;
                this.DragStarted();
            }
        }

        public void DragStarted()
        {
            this._oPoint = new Point(this.transform.TranslateX, this.transform.TranslateY);
            LogHelper.LogInfo(string.Format("_oPoint:\tX:{0},Y:{1}", this._oPoint.X, this._oPoint.Y), this.GetType(), MethodBase.GetCurrentMethod());
        }

        private void OnDragDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            if (this.isGestureOnTarget)
            {
                if (this.Mutexes)
                {
                    return;
                }
                this.DragDelta(e);
                this._ePoint = e.DeltaManipulation.Translation;
                this._cPoint = e.CumulativeManipulation.Translation;
                //if (this.IsDragHorizontal)
                //{
                //    if (this.IsComicFront() || this.IsComicRear())
                //    {
                //        return;
                //    }
                //    double left = Canvas.GetLeft(this.CanvasImageView);
                //    Canvas.SetLeft(this.CanvasImageView, left + this._ePoint.X);
                //}
            }
        }

        public void DragDelta(System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            double x = this._oPoint.X;
            Point translation = e.DeltaManipulation.Translation;
            this._oPoint.X = (x + translation.X);
            double y = this._oPoint.Y;
            Point point = e.DeltaManipulation.Translation;
            this._oPoint.Y = (y + point.Y);
            //
            //LogHelper.LogInfo(string.Format("_oPoint:\tX:{0},Y:{1}", this._oPoint.X, this._oPoint.Y), this.GetType(), MethodBase.GetCurrentMethod());
            LogHelper.LogInfo(string.Format("point:\tX:{0},Y:{1}", point.X, point.Y), this.GetType(), MethodBase.GetCurrentMethod());
            //
            if (this.transform.ScaleX > 1)
            {
                this.transform.TranslateX = (this._oPoint.X);
            }
            if (e.DeltaManipulation.Translation.Y > 0)
            {
                if (this.transform.ScaleY <= 1 && this.transform.TranslateY >= this.TransfromY)
                {
                    this.transform.TranslateY = (this.TransfromY);
                    return;
                }
                this.transform.TranslateY = (this._oPoint.Y);
                return;
            }
            if (this.transform.ScaleY <= 1)
            {
                if (this.DistanceY <= 0)
                {
                    return;
                }
                if (this.transform.TranslateY <= -this.DistanceY)
                {
                    this.transform.TranslateY = (-this.DistanceY);
                    return;
                }
            }
            this.transform.TranslateY = (this._oPoint.Y);
        }

        private void OnDragCompleted()
        {
            LogHelper.LogInfo(string.Format("_cPoint:\tX:{0},Y:{1}", this._cPoint.X, this._cPoint.Y), this.GetType(), MethodBase.GetCurrentMethod());
            if (this.isGestureOnTarget)
            {
                if (this.Mutexes)
                {
                    return;
                }
                //if (Math.Abs(this._cPoint.X) <= Math.Abs(this._cPoint.Y))
                //{
                //    //this.ScrollTo(TscrollModel.EBack, this._cPoint.X);
                //}
                //else
                //{
                //    if (Math.Abs(this._cPoint.X) < 0)
                //    {
                //        //this.ScrollTo(TscrollModel.EBack, this._cPoint.X);                                    
                //        return;
                //    }
                //    if (this.IsDragHorizontal)
                //    {
                //        //this.ChapteTurnImgNav(this._cPoint.X <= 0, this._cPoint.X);
                //        return;
                //    }
                //}
                //
                double scaleY = this.transform.ScaleY * this.middleImage.ActualHeight;
                double scaleX = this.transform.ScaleX * this.middleImage.ActualWidth;
                LogHelper.LogInfo(string.Format("Scale:\tscaleX:{0},scaleY:{1}", scaleX, scaleY), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }

        private void OnFlick(object sender, System.Windows.Input.ManipulationCompletedEventArgs e)
        {
            bool flag = this.isGestureOnTarget;
        }
        #endregion  ********************手势拖拽********************

        #region ********************手势缩放********************
        private void OnPinchStarted(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            if (this.isGestureOnTarget)
            {
                this.PinchStarted();
            }
        }

        public void PinchStarted()
        {
            this.RestS.Stop();
        }

        private void OnPinchDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            if (this.isGestureOnTarget)
            {
                this.PinchDelta(e);
            }
        }

        public void PinchDelta(System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            CompositeTransform compositeTransform = this.transform;
            compositeTransform.ScaleX = (compositeTransform.ScaleX * e.PinchManipulation.DeltaScale);
            CompositeTransform compositeTransform1 = this.transform;
            compositeTransform1.ScaleY = (compositeTransform1.ScaleY * e.PinchManipulation.DeltaScale);
            this.transform.ScaleX = (e.PinchManipulation.CumulativeScale);
            this.transform.ScaleY = (e.PinchManipulation.CumulativeScale);
            e.Handled = true;
        }

        private void OnPinchCompleted()
        {
            if (this.isGestureOnTarget)
            {
                this.PinchCompleted();
            }
        }

        public void PinchCompleted()
        {
            if (this.transform.ScaleX < 1)
            {
                this.RestSx.To = (new double?(1));
                this.RestSy.To = (new double?(1));
                this.RestS.Begin();
                CompositeTransform compositeTransform = this.transform;
                double num = 1;
                this.transform.ScaleX = num;
                compositeTransform.ScaleY = num;
            }
            else if (this.transform.ScaleX > 2)
            {
                this.RestSx.To = (new double?(2));
                this.RestSy.To = (new double?(2));
                this.RestS.Begin();
                CompositeTransform compositeTransform1 = this.transform;
                double num = 2;
                this.transform.ScaleX = num;
                compositeTransform1.ScaleY = num;
            }
            this.IsDragHorizontal = this.transform.ScaleX <= 1;
            this.IsDoubleScale = this.transform.ScaleX > 1;
        }
        #endregion ********************手势缩放********************

        #region ********************双击缩放********************
        public double TransfromY;
        private bool IsDoubleScale = false;
        private void LayoutRoot_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.pIsDoubleTap = true;
            this.popupBrightness.IsOpen = false;
            this.popupContent.IsOpen = false;
            this.popupProgress.IsOpen = false;
            this.ApplicationBar.IsVisible = false;
            this.OnDoubleTap(sender, e);
        }

        public void OnDoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.Mutexes = true;
            if (this.transform.ScaleX < 2)
            {
                IsDoubleScale = true;
                double num = 2;
                this.RestSx.To = (new double?(num));
                this.RestSy.To = (new double?(num));
                this.RestS.Begin();
                this.transform.ScaleY = (num);
                this.transform.ScaleX = (num);
                this.IsDragHorizontal = false;
                return;
            }
            IsDoubleScale = false;
            double num1 = 1;
            this.RestSx.To = (new double?(num1));
            this.RestSy.To = (new double?(num1));
            this.RestS.Begin();
            this.transform.ScaleY = (num1);
            this.transform.ScaleX = (num1);
            this.transform.TranslateX = (0);
            this.transform.TranslateY = (this.TransfromY);
            this.IsDragHorizontal = true;
        }

        private void Story_OnCompleted(object sender, EventArgs e)
        {
            this.Mutexes = false;
        }
        #endregion ********************双击缩放********************
        #endregion ******************************手势绽放控制******************************













































        #region ******************************手势绽放控制******************************
        //private const double doubleTapScale = 2;
        //private bool isDoubleScale = false;

        //#region Manipulation
        //void AddManipulation()
        //{
        //    this.ManipulationDelta += ComicReadPage_ManipulationDelta;
        //    this.ManipulationStarted += ComicReadPage_ManipulationStarted;
        //    this.ManipulationCompleted += ComicReadPage_ManipulationCompleted;
        //}

        //void RemoveManipulation()
        //{
        //    this.ManipulationDelta -= ComicReadPage_ManipulationDelta;
        //    this.ManipulationStarted -= ComicReadPage_ManipulationStarted;
        //    this.ManipulationCompleted -= ComicReadPage_ManipulationCompleted;
        //}

        //void ComicReadPage_ManipulationStarted(object sender, System.Windows.Input.ManipulationStartedEventArgs e)
        //{

        //}

        //void ComicReadPage_ManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        //{

        //}

        //void ComicReadPage_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e)
        //{
        //    e.Handled = true;
        //    FrameworkElement originalSource = e.OriginalSource as FrameworkElement;
        //    Point point = e.ManipulationContainer.TransformToVisual(this).Transform(e.ManipulationOrigin);
        //    if (this.currentDbImageIndex <= 0
        //        && (e.TotalManipulation.Translation.X > 0
        //        || (e.TotalManipulation.Translation.X == 0 && point.X < 240 && (point.Y < 200 || point.Y > 600))))
        //    {
        //        MessageToastManager.Show("已经是本章节的首页了！");
        //        return;
        //    }
        //    if (this.currentDbImageIndex >= this.dbImages.Count - 1
        //        & (e.TotalManipulation.Translation.X < 0
        //        || (e.TotalManipulation.Translation.X == 0 && point.X > 240 && (point.Y < 200 || point.Y > 600))))
        //    {
        //        MessageToastManager.Show("已经是本章节的最后一页了！");
        //        return;
        //    }
        //    this.OnTouchFlick(originalSource, point, e.TotalManipulation.Translation.X);
        //}

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="touchTarget"></param>
        ///// <param name="position"></param>
        ///// <param name="xTotal">滑动值，如果没有进行左右滑动则为0</param>
        //private void OnTouchFlick(FrameworkElement touchTarget, Point position, double xTotal)
        //{
        //    //手势滑动才翻页
        //    if (xTotal < 0)
        //    {
        //        LogHelper.LogInfo("Next");
        //        SetImageNextOrPrevious(NextOrPrevious.Next);
        //        return;
        //    }
        //    if (xTotal > 0)
        //    {
        //        LogHelper.LogInfo("Previous");
        //        SetImageNextOrPrevious(NextOrPrevious.Previous);
        //        return;
        //    }

        //    //中间区域则弹出菜单
        //    if (position.Y > 200 && position.Y < 600 && position.X < 340 && position.X > 140)
        //    {
        //        LogHelper.LogInfo("ApplicationBar");
        //        this.ApplicationBar.IsVisible = !this.ApplicationBar.IsVisible;
        //        this.popupProgress.IsOpen = this.ApplicationBar.IsVisible;
        //        this.popupContent.IsOpen = false;
        //        this.popupBrightness.IsOpen = false;
        //        string popupTitle = string.Empty;
        //        if (this.currentComic != null)
        //            popupTitle += this.currentComic.BigbookName;
        //        if (this.currentComicChapter != null)
        //            popupTitle += " " + this.currentComicChapter.Name;
        //        this.txtPopupProgressTitle.Text = popupTitle;
        //        this.txtPopupBrightnessTitle.Text = popupTitle;
        //        return;
        //    }
        //}

        //public enum NextOrPrevious
        //{
        //    Next,
        //    Previous
        //}

        //private void SetImageNextOrPrevious(NextOrPrevious nextOrPrevious)
        //{
        //    if (nextOrPrevious == NextOrPrevious.Previous)
        //    {
        //        this.currentDbImageIndex = Convert.ToInt32(this.middleImage.Tag);
        //        if (this.currentDbImageIndex <= 0)
        //        {
        //            this.currentDbImageIndex = 0;
        //            return;
        //        }
        //        if (this.currentDbImageIndex - 2 > 0)
        //        {
        //            this.leftImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[currentDbImageIndex - 1]);
        //        }
        //        this.currentDbImageIndex--;
        //        this.middleImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[currentDbImageIndex]);
        //        this.middleImage.Tag = this.currentDbImageIndex;
        //        this.rightImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[currentDbImageIndex], true);
        //        //
        //        //this.leftImage.Visibility = System.Windows.Visibility.Visible;
        //        //this.rightImage.Visibility = System.Windows.Visibility.Collapsed;
        //    }
        //    else if (nextOrPrevious == NextOrPrevious.Next)
        //    {
        //        this.currentDbImageIndex = Convert.ToInt32(this.middleImage.Tag);
        //        if (this.currentDbImageIndex < 0)
        //            this.currentDbImageIndex = 0;
        //        //首页                
        //        this.leftImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[currentDbImageIndex]);
        //        this.currentDbImageIndex++;
        //        //LogHelper.LogInfo("Next:\t" + this.currentDbImageIndex, this.GetType(), MethodBase.GetCurrentMethod());
        //        if (this.currentDbImageIndex < this.dbImages.Count)
        //        {
        //            this.middleImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[currentDbImageIndex]);
        //            this.middleImage.Tag = this.currentDbImageIndex;
        //        }
        //        //this.currentDbImageIndex++;
        //        if ((this.currentDbImageIndex + 1) < this.dbImages.Count)
        //        {
        //            this.rightImage.Source = this.LoadBitmapImageFromDbImage(this.dbImages[currentDbImageIndex + 1], true);
        //        }
        //        //
        //        //this.leftImage.Visibility = System.Windows.Visibility.Collapsed;
        //        //this.rightImage.Visibility = System.Windows.Visibility.Visible;
        //    }

        //    this.sliderPopupProgress.Value = Convert.ToInt32(this.middleImage.Tag) + 1;//因为是从零开始计数
        //}
        //#endregion Manipulation

        //private void reset()
        //{
        //    if (transform.ScaleX < 1)
        //    {
        //        rest_s_x.To = 1;
        //        rest_s_y.To = 1;
        //        rest_s.Begin();
        //        transform.ScaleY = transform.ScaleX = 1f;
        //    }
        //    else if (transform.ScaleX > 3)
        //    {
        //        rest_s_x.To = 3;
        //        rest_s_y.To = 3;
        //        rest_s.Begin();
        //        transform.ScaleY = transform.ScaleX = 3f;
        //    }
        //    double tsx = (transform.ScaleX - 1) * this.middleImage.ActualWidth / 2;
        //    double tsy = (transform.ScaleY - 1) * this.middleImage.ActualHeight / 2;
        //    rest_x_t.To = transform.TranslateX;
        //    double x = transform.TranslateX - tsx;
        //    if (x > 0)
        //    {
        //        rest_x_t.To = tsx;
        //    }
        //    double x2 = transform.TranslateX + tsx;
        //    if (x2 < 0)
        //    {
        //        rest_x_t.To = -tsx;
        //    }
        //    rest_y_t.To = transform.TranslateY;
        //    double y = transform.TranslateY - tsy;
        //    if (y > 0)
        //    {
        //        rest_y_t.To = tsy;
        //    }
        //    double y2 = transform.TranslateY + tsy;
        //    if (y2 < 0)
        //    {
        //        rest_y_t.To = -tsy;
        //    }
        //    if (x > 0 || x2 < 0 || y > 0 || y2 < 0)
        //    {
        //        rest_t.Begin();
        //        transform.TranslateX = tsx;
        //        transform.TranslateY = tsy;
        //    }
        //}

        //#region 双击缩放
        //private void GestureListener_DoubleTap(object sender, GestureEventArgs e)
        //{
        //    if (transform.ScaleX < doubleTapScale)
        //    {
        //        this.RemoveManipulation();
        //        double s = doubleTapScale;
        //        rest_s_x.To = s;
        //        rest_s_y.To = s;
        //        rest_s.Begin();
        //        transform.ScaleY = s;
        //        transform.ScaleX = s;
        //        this.isDoubleScale = true;
        //    }
        //    else
        //    {
        //        this.AddManipulation();
        //        double s = 1f;
        //        rest_s_x.To = s;
        //        rest_s_y.To = s;
        //        rest_s.Begin();
        //        transform.ScaleY = s;
        //        transform.ScaleX = s;
        //        this.isDoubleScale = false;
        //        reset();
        //    }
        //}
        //#endregion 双击缩放

        //#region 手势缩放
        //private double initialScale = 1f;
        //private void GestureListener_PinchStarted(object sender, PinchStartedGestureEventArgs e)
        //{
        //    rest_s.Stop();
        //    initialScale = transform.ScaleX;
        //}

        //private void GestureListener_PinchDelta(object sender, PinchGestureEventArgs e)
        //{
        //    var s = initialScale * e.DistanceRatio;
        //    if (s > 4f)
        //    {
        //        s = 4f;
        //    }
        //    animx_s.To = s;
        //    animy_s.To = s;
        //    story_s.Begin();
        //}

        //private void GestureListener_PinchCompleted(object sender, PinchGestureEventArgs e)
        //{
        //    if (transform.ScaleX <= 1)
        //    {
        //        this.isDoubleScale = false;
        //    }
        //    else
        //    {
        //        this.isDoubleScale = true;
        //    }
        //    reset();
        //}
        //#endregion 手势缩放

        //#region 拖动效果
        //private Point dragPoint;
        //private void GestureListener_DragStarted(object sender, DragStartedGestureEventArgs e)
        //{
        //    //dragPoint = new Point(transform.TranslateX, transform.TranslateY);
        //}

        //private void GestureListener_DragDelta(object sender, DragDeltaGestureEventArgs e)
        //{
        //    //var p = e.GetPosition(sender as UIElement);
        //    //LogHelper.LogInfo("GestureListener_DragDelta:\t" + e.HorizontalChange);
        //    //dragPoint.X += e.HorizontalChange;
        //    //if (transform.ScaleY > 1)
        //    //{
        //    //    dragPoint.Y += e.VerticalChange;
        //    //}
        //    //animx.To = dragPoint.X;
        //    //animy.To = dragPoint.Y;
        //    //story.Begin();
        //    ////横屏时
        //    //if (this.Orientation == PageOrientation.Portrait || this.Orientation == PageOrientation.PortraitDown || this.Orientation == PageOrientation.PortraitUp)
        //    //{
        //    //    if (e.HorizontalChange > 0)
        //    //    {
        //    //        //上一页
        //    //        this.leftImage.Visibility = System.Windows.Visibility.Visible;
        //    //        this.rightImage.Visibility = System.Windows.Visibility.Collapsed;
        //    //    }
        //    //    else if (e.HorizontalChange < 0)
        //    //    {
        //    //        //下一页
        //    //        this.leftImage.Visibility = System.Windows.Visibility.Collapsed;
        //    //        this.rightImage.Visibility = System.Windows.Visibility.Visible;
        //    //    }
        //    //}
        //    //else if (this.Orientation == PageOrientation.Landscape || this.Orientation == PageOrientation.LandscapeLeft || this.Orientation == PageOrientation.LandscapeRight)
        //    //{

        //    //}
        //}

        //private void GestureListener_DragCompleted(object sender, DragCompletedGestureEventArgs e)
        //{
        //    //reset();
        //}
        //#endregion 拖动效果
        #endregion ******************************手势绽放控制******************************

    }
}